﻿using System.Collections.Concurrent;
using System.Net.Sockets;

namespace CS.Beehive
{
    /// <summary>
    /// 连接队列
    /// </summary>
    public class ConnectionQueue
    {
        private readonly ConcurrentQueue<Socket> _connectingQueue = new ConcurrentQueue<Socket>();

        public ConnectionQueue()
        {
        }

        public void Clear()
        {
            lock (this)
            {
                for (int i = 0; i < _connectingQueue.Count; i++)
                {
                    Dequeue();
                }
            }
        }

        /// <summary>
        /// 队列元素数量
        /// </summary>
        public int Count
        {
            get { return _connectingQueue.Count; }
        }

        /// <summary>
        /// 取出一个元素，取不到时为null
        /// </summary>
        /// <returns></returns>
        public Socket Dequeue()
        {
            if (Count > 0)
            {
                Socket item;
                return _connectingQueue.TryDequeue(out item) ? item : null;
            }
            return null;
        }

        /// <summary>
        /// 将无素存入队尾
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue(Socket item)
        {
            _connectingQueue.Enqueue(item);
        }


    }
}